package com.example.hrsystem.ui.approval.overtime;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.ApprovalStatus;
import com.example.hrsystem.workflow.ApprovalUtils;
import com.example.hrsystem.workflow.ApprovalViewModel;
import com.example.hrsystem.workflow.model.OvertimeRequest;

/**
 * 加班申请详情Activity
 * 用于显示加班申请的详细信息和处理审批操作
 */
public class OvertimeRequestDetailActivity extends AppCompatActivity {
    private ApprovalViewModel viewModel;
    
    private TextView requestNumberTextView;
    private TextView statusTextView;
    private TextView statusBadge;
    private TextView requesterNameTextView;
    private TextView createdAtTextView;
    private TextView overtimeTypeTextView;
    private TextView overtimeDateTextView;
    private TextView timeRangeTextView;
    private TextView hoursTextView;
    private TextView reasonTextView;
    private TextView approvalHistoryTextView;
    
    private EditText commentEditText;
    private Button approveButton;
    private Button rejectButton;
    private ProgressBar progressBar;
    
    private int requestId; // Changed from String to int
    private boolean isApprover = false; // 实际应用中应从权限系统获取
    private int currentUserId = 1001; // 默认审批人ID，实际应用中应从登录信息获取
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_overtime_request_detail);

        // 获取申请ID
        String requestIdStr = getIntent().getStringExtra("request_id");
        if (requestIdStr == null || requestIdStr.isEmpty()) {
            Toast.makeText(this, "无效的请求ID", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        try {
            requestId = Integer.parseInt(requestIdStr);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "无效的请求ID格式", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ApprovalViewModel.class);

        // 初始化UI组件
        initUI();

        // 设置按钮点击事件
        setupButtonListeners();

        // 加载申请详情
        loadOvertimeRequestDetail();

        // 观察审批结果
        observeApprovalResult();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        requestNumberTextView = findViewById(R.id.request_number_text_view);
        statusTextView = findViewById(R.id.status_text_view);
        statusBadge = findViewById(R.id.status_badge);
        requesterNameTextView = findViewById(R.id.requester_name_text_view);
        createdAtTextView = findViewById(R.id.created_at_text_view);
        overtimeTypeTextView = findViewById(R.id.overtime_type_text_view);
        overtimeDateTextView = findViewById(R.id.overtime_date_text_view);
        timeRangeTextView = findViewById(R.id.time_range_text_view);
        hoursTextView = findViewById(R.id.hours_text_view);
        reasonTextView = findViewById(R.id.reason_text_view);
        approvalHistoryTextView = findViewById(R.id.approval_history_text_view);
        
        commentEditText = findViewById(R.id.comment_edit_text);
        approveButton = findViewById(R.id.approve_button);
        rejectButton = findViewById(R.id.reject_button);
        progressBar = findViewById(R.id.progress_bar);
    }

    /**
     * 设置按钮点击事件
     */
    private void setupButtonListeners() {
        approveButton.setOnClickListener(v -> handleApproval(true));
        rejectButton.setOnClickListener(v -> handleApproval(false));
    }

    /**
     * 加载加班申请详情
     */
    private void loadOvertimeRequestDetail() {
        progressBar.setVisibility(View.VISIBLE);
        
        // 从ViewModel加载详情
        OvertimeRequest overtimeRequest = viewModel.getOvertimeRequestById(requestId);
        progressBar.setVisibility(View.GONE);
        
        if (overtimeRequest != null) {
            displayOvertimeRequestDetail(overtimeRequest);
            updateApprovalUI(overtimeRequest);
        } else {
            Toast.makeText(this, "无法加载申请详情", Toast.LENGTH_SHORT).show();
        }
        
        // 观察错误信息
        viewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 显示加班申请详情
     */
    private void displayOvertimeRequestDetail(OvertimeRequest overtimeRequest) {
        // 基本信息 (暂时使用ID代替，因为没有requestNumber字段)
        requestNumberTextView.setText("加班申请 #" + overtimeRequest.getId());
        
        // 状态显示
        String status = overtimeRequest.getStatus();
        statusTextView.setText(status);
        statusBadge.setText(status);
        // 暂时移除状态标签背景色设置，因为该方法不存在
        
        // 申请人和创建时间
        // 暂时不显示申请人名称，因为该方法不存在
        createdAtTextView.setText(ApprovalUtils.formatDateTime(overtimeRequest.getCreatedAt()));
        
        // 加班详情
        overtimeTypeTextView.setText(overtimeRequest.getOvertimeType());
        overtimeDateTextView.setText(ApprovalUtils.formatDate(overtimeRequest.getOvertimeDate()));
        timeRangeTextView.setText(String.format("%s - %s", 
                ApprovalUtils.formatTime(overtimeRequest.getStartTime()),
                ApprovalUtils.formatTime(overtimeRequest.getEndTime())));
        hoursTextView.setText(String.format("%.1f小时", overtimeRequest.getHours()));
        reasonTextView.setText(overtimeRequest.getReason());
        
        // 审批历史
        approvalHistoryTextView.setText("暂无审批历史"); // 暂时设置为默认文本
    }

    /**
     * 更新审批UI，根据权限和状态显示或隐藏审批按钮
     */
    private void updateApprovalUI(OvertimeRequest overtimeRequest) {
        ApprovalStatus status = ApprovalStatus.fromValue(overtimeRequest.getStatus());
        
        // 如果是审批人且状态为待审批，则显示审批按钮
        if (isApprover && !status.isFinalState()) {
            approveButton.setVisibility(View.VISIBLE);
            rejectButton.setVisibility(View.VISIBLE);
            commentEditText.setVisibility(View.VISIBLE);
        } else {
            approveButton.setVisibility(View.GONE);
            rejectButton.setVisibility(View.GONE);
            commentEditText.setVisibility(View.GONE);
        }
    }

    /**
     * 处理审批操作
     */
    private void handleApproval(boolean isApproved) {
        String comment = commentEditText.getText().toString().trim();
        
        progressBar.setVisibility(View.VISIBLE);
        
        // 暂时注释掉审批功能，因为需要taskId而非requestId
        // 当有了正确的taskId后可以取消注释以下代码
        // if (isApproved) {
        //     viewModel.approveTask(taskId, currentUserId, comment);
        // } else {
        //     viewModel.rejectTask(taskId, currentUserId, comment);
        // }
        Toast.makeText(this, "审批功能暂不可用", Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 观察审批结果
     */
    private void observeApprovalResult() {
        // 观察加载状态
        viewModel.getIsLoading().observe(this, isLoading -> {
            if (isLoading) {
                progressBar.setVisibility(View.VISIBLE);
                approveButton.setEnabled(false);
                rejectButton.setEnabled(false);
            } else {
                progressBar.setVisibility(View.GONE);
                approveButton.setEnabled(true);
                rejectButton.setEnabled(true);
            }
        });
        
        // 观察审批成功
        viewModel.getOperationSuccess().observe(this, isSuccess -> {
            if (isSuccess != null && isSuccess) {
                Toast.makeText(this, "审批操作成功", Toast.LENGTH_SHORT).show();
                // 重新加载详情以更新状态
                loadOvertimeRequestDetail();
            }
        });
        
        // 观察错误信息
        viewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }
}